package com.mach.platform.api.service;

import com.mach.platform.api.domain.WxUser;
import com.mach.platform.api.repository.WxUserRepo;
import com.mach.platform.api.util.Base64Util;
import com.mach.platform.api.util.ImageUtil;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.io.UnsupportedEncodingException;

@Service
public class LoginServiceImpl {

    @Autowired
    private WxUserRepo userRepo;

    /**
     * 保存用户信息，写进缓存
     * @param openId
     * @param nickName 用户昵称
     * @return
     */
    @Transactional(rollbackOn = Exception.class)
    public void saveUser(String openId, String nickName) {
        WxUser wxUser = userRepo.findByOpenId(openId);
        if (null == wxUser) {
            WxUser user = new WxUser();
            user.setUserId(System.currentTimeMillis());
            user.setOpenId(openId);
            // 昵称可能含有微信表情，需要编码
            nickName = Base64Util.base64Coding(nickName);
            user.setNickName(nickName);
            String avatarPath = ImageUtil.getAvatarShowPath(openId);
            user.setAvatarPath(avatarPath);
            // 保存用户信息
            userRepo.save(user);
        }
    }


    /**
     * 查询小程序用户信息
     * @param openId
     * @return
     */
    public WxUser getWxUserByOpenId(String openId) {
        return userRepo.findByOpenId(openId);
    }


}
